<template>
  <div class="proMeg">
    <!-- <div class="proMeg_tit">
      <span>产品管理</span>
      
    </div> -->
    <gl-breadcrumb class="mb15"
                   text="产品管理"></gl-breadcrumb>
    <div class="proMeg_main">
      <div class="proMeg_main_nav">
        <el-select class="mr20"
                   v-model="contacts_id"
                   clearable
                   placeholder="请选择客户"
                   @change="getList">
          <el-option v-for="item in customersList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-select class="mr20"
                   v-model="status"
                   clearable
                   placeholder="请选择状态"
                   @change="getList">
          <el-option v-for="item in statusList"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value">
          </el-option>
        </el-select>
        <el-input class="mr20"
                  v-model="proName"
                  style="width:200px"
                  placeholder="请输入产品名称"></el-input>
        <div>
          <el-button type="primary"
                     icon="el-icon-search"
                     @click="getList">
            搜索
          </el-button>
          <el-button type="primary"
                     icon="el-icon-plus"
                     @click="add">
            新建
          </el-button>
        </div>
      </div>
      <div class="proMeg_main_box">
        <gl-table @button="buttonClick"
                  :data="data"
                  :columns="columns">
          <el-button type="text"
                     slot="sum"
                     slot-scope="scope"
                     @click="numClick(scope.row)">
            {{scope.row.act_sum+'/'+scope.row.sum}}
          </el-button>

        </gl-table>
        <gl-pagination :curr="curr"
                       :size="pageSize"
                       :total="total"
                       @callback="currChange"></gl-pagination>
      </div>
    </div>
    <Gldelbtn :show="showDel"
              :text="dialogText"
              @cancel="closeDel"
              @determine="determine"></Gldelbtn>
    <el-dialog :title="dialogTitle"
               :visible.sync="dialogVis"
               :before-close="handleClose">
      <gl-form :form="form"
               ref="glForm"
               :formLabel="formLabel"
               :must="must">
        <template>
          <div slot="integrated"
               class="intBox">
            <div v-for="(item,index) in integratedList"
                 :key="index"
                 class="itemBox"
                 @mouseover="item.show = true"
                 @mouseout="item.show = false">
              <span class="name">{{item.tpa_name}}</span>
              <!-- <span class="del">x</span> -->
              <i class="el-icon-close"
                 :class="item.show?'show':'del'"
                 @click="delItem(item.tpa_id,'int')"></i>
            </div>
            <div class="add"
                 @click="addIntegrated">
              <span class="addico"> + </span>
              <span class="addbox"> 添加 </span>
            </div>
          </div>
        </template>
        <template>
          <div slot='tag'
               class="tagBox">
            <div v-for="(item,index) in tagList"
                 :key="index"
                 class="itemBox"
                 @mouseover="item.show = true"
                 @mouseout="item.show = false">
              <span class="name">{{item.channel_name}}</span>
              <!-- <span class="del">x</span> -->
              <i class="el-icon-close"
                 :class="item.show?'show':'del'"
                 @click="delItem(item.channel_id,'tag')"></i>

            </div>
            <div class="add"
                 @click="addChannel">
              <span class="addico"> + </span>
              <span class="addbox">添加</span>
            </div>
          </div>
        </template>
      </gl-form>
      <el-dialog :title="addtitle"
                 :visible.sync="addDialog"
                 append-to-body>

        <div v-if="Thired"
             class="addThired clearfix">
          <div class="ThiredLi"
               v-for="(item,index) in thiredList"
               :key="index">
            <el-checkbox v-model="item.checked"
                         :label="item.tpa_name"
                         border
                         size="medium"></el-checkbox>
          </div>
        </div>

        <div v-else
             class="addChannel clearfix">
          <div class="ChannelLi"
               v-for="(item,index) in ChannelList"
               :key="index">
            <el-checkbox v-model="item.checked"
                         :label="item.channel_name"
                         border
                         size="medium"></el-checkbox>
          </div>
        </div>

        <div slot="footer"
             class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary"
                     @click="submit">确定</el-button>
        </div>
      </el-dialog>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVis = false">取 消</el-button>
        <el-button type="primary"
                   @click="addProduct">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
  name: 'productMeg',
  computed: {
    ...mapGetters(['userInfo'])
  },
  data() {
    return {
      show: false,
      company_id: '',
      Thired: true,
      customersList: [], //客户下拉列表
      contacts_id: '',
      statusList: [
        { label: '启用', value: '1' },
        { label: '禁用', value: '2' }
      ], //状态列表
      status: '',
      proName: '',
      data: [],
      columns: [
        { label: '产品ID', prop: 'id' },
        { label: '产品名称', prop: 'name' },
        { label: '激活情况', slot: 'sum' },
        { label: '授权方式', prop: 'aw_name' },
        { label: '使用期限', prop: 'endtime', format: 's%天' },
        { label: '所属客户', prop: 'customer_name' },
        { label: '操作', btns: ['编辑', '删除'], class: 'btn' }
      ],
      curr: 1,
      pageSize: 10,
      total: 0,
      dialogVis: false,
      dialogTitle: '',
      form: {
        name: '',
        customer_id: '',
        auth_id: '',
        aw_id: '',
        endtime: '',
        tpa_id: '',
        channel_id: '',
        sum_times: '',
        remark: ''
      },
      formLabel: [
        {
          label: '选择客户',
          prop: 'customer_id',
          options: [],
          placeholder: '请输入'
        },
        { label: '产品名称：', prop: 'name', placeholder: '请输入' },
        {
          label: '授权方式：',
          prop: 'auth_id',
          placeholder: '请输入',
          options: []
        },
        {
          label: '激活方式：',
          prop: 'aw_id',
          placeholder: '请输入',
          options: []
        },
        { label: '使用期限：', prop: 'endtime', placeholder: '请输入' },
        { label: '通讯时长：', prop: 'sum_times', placeholder: '请输入' },
        { label: '第三方集成：', prop: 'tpa_id', slot: 'integrated' },
        { label: '渠道标签：', prop: 'channel_id', slot: 'tag' },
        {
          label: '产品描述：',
          prop: 'remark',
          type: 'textarea',
          placeholder: '请输入'
        }
      ],
      integratedList: [],
      thiredList: [],
      tagList: [],
      ChannelList: [],
      must: 'customer_id,name,auth_id,aw_id,endtime,sum_times',
      showDel: false,
      dialogText: '',
      addDialog: false,
      addtitle: '',
      product_id: ''
    }
  },
  created() {
    this.company_id = this.userInfo.company_id
    this.getList() // 列表
    this.getCustomersList() // 客户列表
    this.getThired() // 第三方集成
    this.getChannelList() // 渠道
    this.getAuths() // 获取授权方式列表
    this.getAW() // 获取激活方式列表
  },
  watch: {
    dialogVis(val) {
      if (!val) {
        this.form = {}
      }
    }
  },
  methods: {
    numClick(row) {
      //   console.log(row)
      this.$router.push({
        path: '/customer/RegisterDevice',
        query: {
          type: 'pro',
          id: row.id,
          name: row.name,
          sum: row.sum,
          act_sum: row.act_sum
        }
      })
    },
    delItem(index, str) {
      index = index.toString()

      if (str == 'int') {
        let tempArr = this.form.tpa_id.split(',')
        if (tempArr.indexOf(index) != -1) {
          tempArr.splice(tempArr.indexOf(index), 1)
        }
        this.integratedList.map((e, i) => {
          if (e.tpa_id == index) {
            this.integratedList.splice(i, 1)
          }
        })
        this.form.tpa_id = tempArr.join(',')
      } else if (str == 'tag') {
        let temp = this.form.channel_id.split(',')
        if (temp.indexOf(index) != -1) {
          temp.splice(temp.indexOf(index), 1)
        }
        this.tagList.map((e, i) => {
          if (e.channel_id == index) {
            this.tagList.splice(i, 1)
          }
        })
        this.form.channel_id = temp.join(',')
      }
    },
    cancel() {
      this.addDialog = false
      this.thiredList.map(e => {
        if (this.form.tpa_id.includes(e.tpa_id)) {
          e.checked = true
        } else {
          e.checked = false
        }
      })
      this.ChannelList.map(e => {
        if (this.form.channel_id.includes(e.channel_id)) {
          e.checked = true
        } else {
          e.checked = false
        }
      })
    },
    submit() {
      this.integratedList = this.thiredList.filter(item => {
        return item.checked == true
      })
      let temp = []
      this.integratedList.map(e => {
        temp.push(e.tpa_id)
      })
      this.form.tpa_id = temp.join(',')

      this.tagList = this.ChannelList.filter(item => {
        return item.checked == true
      })
      let tmp = []
      this.tagList.map(e => {
        tmp.push(e.channel_id)
      })
      this.form.channel_id = tmp.join(',')

      // this.thiredList.map(e=>(e.checked = false))
      //   console.log(this.form.tpa_id)
      //   console.log(this.form.channel_id)

      this.addDialog = false
    },
    addProduct() {
      if (this.$refs.glForm.validate()) {
        this.http
          .$post('admin/product.api/add', this.form)
          .then(r => {
            //   console.log(r)
            this.dialogVis = false
            this.$message.success('新增成功')
            this.getList()
          })
          .catch(this.$err)
      } else {
        return this.$message.error('请确认输入是否完整无误')
      }
    },
    addIntegrated() {
      this.addtitle = '第三方添加'
      this.addDialog = true
      this.Thired = true
      //   this.List.splice(0,this.List.length,...this.thiredList)
    },
    addChannel() {
      this.addtitle = '渠道添加'
      this.addDialog = true
      this.Thired = false
      //   this.List.splice(0,this.List.length,...this.ChannelList)
    },
    getThired() {
      this.http
        .$post('admin/thirdpa.api/all_lists')
        .then(r => {
          //   console.log(r)
          this.thiredList = r.map(e => ({ checked: false, show: false, ...e }))
        })
        .catch(this.$err)
    },
    getChannelList() {
      this.http
        .$post('admin/channel.Api/all_lists')
        .then(r => {
          //   console.log(r)
          this.ChannelList = r.map(e => ({ checked: false, show: false, ...e }))
        })
        .catch(this.$err)
    },
    getList(obj) {
      if (obj) {
        this.curr = obj.curr
        this.pageSize = obj.size
      } else {
        this.curr = 1
        this.pageSize = 10
      }
      this.http
        .$post('admin2/product.api/product_list', {
          curr: this.curr,
          limits: this.pageSize,
          customer_id: this.contacts_id,
          status: this.status,
          keyword: this.proName
        },{loading:true})
        .then(r => {
          //   console.log(r)
          this.data = r.list
          this.total = r.total
        })
        .catch(this.$err)
    },
    getCustomersList() {
      this.http
        .$post('admin/customer.api/list_customers', {
          company_id: this.company_id
        })
        .then(r => {
          //   console.log(r)
          if (r && r.length) {
            this.customersList = r
            this.formLabel[0].options = r.map(e => ({
              label: e.name,
              value: e.id
            }))
          }
        })
        .catch(this.$err)
    },
    getAuths() {
      this.http
        .$post('admin/auth.api/list_auths')
        .then(r => {
          //   console.log(r)
          if (r && r.length) {
            this.formLabel[2].options = r.map(e => ({
              label: e.auth_name,
              value: e.auth_id
            }))
          }
        })
        .catch(this.$err)
    },
    getAW() {
      this.http
        .$post('admin/Product.api/get_aw')
        .then(r => {
          //   console.log(r)
          if (r && r.length) {
            this.formLabel[3].options = r.map(e => ({
              label: e.name,
              value: e.id
            }))
          }
        })
        .catch(this.$err)
    },
    delProduct(product_id) {
      this.http
        .$post('admin/product.api/del', {
          product_id
        })
        .then(r => {
          //   console.log(r)
          this.$message.success('删除成功')
          this.getList()
        })
        .catch(this.$err)
    },

    closeDel() {
      this.showDel = false
    },
    determine(code, Vcode) {
      // console.log(code,Vcode);
      if (code == Vcode) {
        this.showDel = false
        this.delProduct(this.product_id)
      } else {
        if (Vcode == '') {
          this.$message.error('验证码不能为空')
        } else {
          this.$message.error('验证码输出错误，请重新输入')
        }
      }
    },
    buttonClick(obj) {
      // console.log(obj)
      this.product_id = obj.row.id
      if (obj.index * 1 === 1) {
        this.dialogText = obj.row.name
        this.showDel = true
      } else {
        // console.log('push New Router')
        this.$router.push({
          path: 'customer/productDetail',
          query: { type: 'product', id: obj.row.id }
        })
      }
    },
    currChange(obj) {
      //   console.log(obj)
      //   this.curr = obj.curr
      //   this.pageSize = obj.size
      //   this.getList(this.curr, this.pageSize)
      this.getList(obj)
    },
    add() {
      this.dialogVis = true
      this.dialogTitle = '新增产品'
      this.$refs.glForm && this.$refs.glForm.clearValidate()
    }
  }
}
</script>
<style lang="less" scoped>
.el-button.el-button--text{
    padding: 0;
}
.addThired,
.addChannel {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
  .ThiredLi,
  .ChannelLi {
    min-width: 170px;
    margin-bottom: 5px;
  }
}
/deep/.el-dialog__header {
  border-bottom: 1px solid #ddd;
}
.proMeg {
  // background-color: #fff;
  .proMeg_tit {
    padding: 15px 0 15px 25px;
    background-color: #fff;
    margin-bottom: 20px;
  }
  .proMeg_main {
    padding: 20px 25px;
    background-color: #fff;
    .proMeg_main_nav {
      display: flex;
    }
    .proMeg_main_box {
      margin-top: 20px;
      /deep/ .el-table .cell {
        .el-button--text {
          &.btn {
            margin: 0;
            span {
              padding: 0 5px;
              border-right: 1px solid #66b1ff;
            }
            &:last-child {
              span {
                border: none;
              }
            }
          }
        }
      }
    }
  }
  .intBox,
  .tagBox {
    display: flex;
    display: -webkit-flex;
    justify-content: flex-start;
    flex-direction: row;
    flex-wrap: wrap;
    .itemBox {
      height: 30px;
      line-height: 30px;
      border: 1px solid #ccc;
      border-radius: 4px;
      margin-right: 16px;
      margin-bottom: 5px;
      position: relative;
      .name {
        // display: inline-block;
        text-align: center;
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        padding: 0 10px;
      }
      .del {
        display: none;
      }
      .show {
        display: inline-block;
        cursor: pointer;
      }
    }
    .add {
      height: 30px;
      line-height: 30px;
      border: 1px dashed #ccc;
      border-radius: 4px;
      padding: 0 8px;
      cursor: pointer;
      .addico {
        margin-right: 4px;
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
}
</style>